package com.mobilesalon.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.mobilesalon.MobileSalonFactory;
import com.mobilesalon.R;
import com.mobilesalon.business.ServiceClientManager;
import com.mobilesalon.model.AppointmentBean;
import com.mobilesalon.provider.ServiceClientContract.Service;
import com.mobilesalon.provider.ServiceClientContract.ServiceClient;
import com.mobilesalon.tools.DateTools;

public class AppointmentDetails extends ListActivity implements OnItemLongClickListener {
	private static final String TAG = AppointmentDetails.class.getName();

	static final int PICK_CONTACT = 1;
	static final int DIALOG_DELETE_SERVICE_CLIENT = 2;
	static final int DIALOG_MSG_DELETE_SERVICE_CLIENT = R.string.dialog_msg_delete_service_client;

	static final int RESULT_APPOINTMENT = 3;

	// ui
	private TextView textClient;
	private TextView textTime;
	private TextView textAmount;

	// model
	private AppointmentBean appointmentBean;
	private long serviceClientIdToDelete;

	// business services
	private ServiceClientManager serviceClientManager;

	// technical
	boolean isRefresh;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.isRefresh = false;

	}

	@Override
	public void onResume() {
		Log.d(TAG, "Start Activity: ServiceAdder");
		super.onResume();

		// business services
		serviceClientManager = MobileSalonFactory.getServiceClientManager();

		setContentView(R.layout.appointment_details);

		// get UI objects
		textClient = (TextView) findViewById(R.id.appointment_detail_display_name);
		textTime = (TextView) findViewById(R.id.appointment_detail_time);
		textAmount = (TextView) findViewById(R.id.appointment_detail_amount);
		this.getListView().setOnItemLongClickListener(this);

		if ( this.appointmentBean == null || ! this.appointmentBean.isIsStored()) {
			this.appointmentBean = getAppointmentIdFromIntent();
			displayHeader();
			isRefresh = true;
		} else {
				refreshHeader(this.appointmentBean.getId());
		}

		refreshList();
	}

	private void displayHeader() {
		textClient.setText(appointmentBean.getClientDisplayName());
		textTime.setText(DateTools.TIME_DATEFORMAT.format(appointmentBean.getDate().getTime()));
		textAmount.setText(String.valueOf(appointmentBean.getPrice()));
	}

	private AppointmentBean getAppointmentIdFromIntent() {
		AppointmentBean appointmentBean = (AppointmentBean) this.getIntent().getParcelableExtra(
				"appointmentBean");
		if (appointmentBean == null) {
			Log.e(TAG, "Start Activity: ServiceAdder");
			throw new IllegalStateException(
					"An object of type AppointmentBean(\"appointmentBean\")must be passed to this activity");
		}
		return appointmentBean;
	}

	private void refreshHeader(long id) {
		this.appointmentBean = serviceClientManager.fetchAppointmentById(id);
		if (appointmentBean == null) {
			Log.e(TAG, "Start Activity: ServiceAdder");
			throw new IllegalStateException("AppointmentId has not been found (" + id + ")");
		}

		this.displayHeader();
	}

	//
	// List behavior
	//
	private void refreshList() {
		Cursor serviceClientCursor = serviceClientManager
				.fetchServiceClientsByAppointmentId(appointmentBean.getId());
		this.startManagingCursor(serviceClientCursor);

		serviceClientCursor.moveToFirst();

		// Create a mapping between database columns and layout fields
		String[] from = new String[] { ServiceClient.CLIENT_DISPLAY_NAME, Service.SERVICE_NAME,
				ServiceClient.PRICE };
		int[] to = new int[] { R.id.service_client_row_display_name,
				R.id.service_client_row_services, R.id.service_client_row_price };

		// Create a cursor adapter and set it to display using a row layout
		SimpleCursorAdapter serviceClientAdapter = new SimpleCursorAdapter(this,
				R.layout.service_client_row, serviceClientCursor, from, to);

		setListAdapter(serviceClientAdapter);
	}

	@Override
	public void onListItemClick(ListView listView, View view, int position, long id) {
		// do nothing
	}

	// delete
	public boolean onItemLongClick(AdapterView<?> adapterView, View arg1, int position, long id) {
		this.showDialog(AppointmentDetails.DIALOG_DELETE_SERVICE_CLIENT);
		this.serviceClientIdToDelete = id;
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case AppointmentDetails.DIALOG_DELETE_SERVICE_CLIENT:
			builder.setTitle(AppointmentDetails.DIALOG_MSG_DELETE_SERVICE_CLIENT);
			builder.setNegativeButton(R.string.button_cancel, null);
			builder.setPositiveButton(R.string.button_ok, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					serviceClientManager.deleteServiceClientById(serviceClientIdToDelete);
					refreshHeader(appointmentBean.getId());
					refreshList();

				}
			});

			break;
		}
		AlertDialog alert = builder.create();
		return alert;
	}

	//
	// Menu behavior
	//
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_appointment_details, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.add_service_client:
			// start ServiceAdderActivity
			Intent intent = new Intent(getApplicationContext(), ServiceAdder.class);
			intent.putExtra("appointmentBean", appointmentBean);
			this.startActivityForResult(intent, RESULT_APPOINTMENT);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK && requestCode == RESULT_APPOINTMENT) {
			this.appointmentBean = (AppointmentBean) data.getParcelableExtra(
			"appointmentBean");
			
		}
	}

}